<template>
  <q-input outlined v-model="deptName" class="col" :label="$t('Dept')" lazy-rules
           :rules="[val => val && val.length > 0 || $t('NeedInput')]" clearable @clear="clearInput">
    <template v-slot:append>
      <q-icon name="assured_workload" @click="deptShow.show()" style="cursor: pointer">
      </q-icon>
    </template>
    <template v-slot:prepend>
      <q-popup-proxy style="width: 750px; max-width: 80vw;" transition-show="scale" transition-hide="scale"
                     ref="deptShow" persistent>
        <q-tree :nodes="deptList" v-model:selected="selectDept" @update:selected="handleSelectDept"
                ref="deptTree"
                label-key="deptName" node-key="deptCode" selected-color="primary"/>
      </q-popup-proxy>
    </template>
  </q-input>
</template>

<script setup>
import {ref, computed, onMounted, toRefs, nextTick, watch} from 'vue'
import {ArrayToTree} from "src/utils/arrayAndTree"
import {postAction} from 'src/api/manage'
const props = defineProps({
  initDeptCode: {
    type: String,
    required: false
  },
})
const { initDeptCode } = toRefs(props)
onMounted(() => {
     getDeptList()
})
watch(() => initDeptCode.value, () => {
  deptCode.value = initDeptCode.value
})
const url = {
  deptListUrl: 'dept/get-dept-list',
}
const deptList = ref([])
const selectDept = ref(null)
const deptShow = ref(null)
const deptTree = ref(null)
const deptCode = ref(null)
const deptData = ref([])
const emit = defineEmits(['update:selectDeptCode'])
const getDeptList = () => {
  deptList.value = []
  postAction(url.deptListUrl, {
    sortBy: 'sort',
    desc: false,
    page: 1,
    pageSize: 99999
  }).then(res => {
    deptData.value = res.data.rows
    deptList.value = ArrayToTree(deptData.value, "deptCode", "parentCode") || []
  })
}
const deptName = computed(() => {
  if (deptCode.value && deptData.value) {
   let nodes = deptData.value.filter((dept)=>{
      if(dept.deptCode == deptCode.value){
        return dept
      }
    })
    let node = nodes&&nodes.length>0?nodes[0]:null
    return node?node.deptName:''
  }else{
    return ''
  }
})
const handleSelectDept = (target) => {
  emit('update:selectDeptCode', target)
  deptCode.value = target
  deptShow.value.hide()
}

const clearInput = (target) =>{
  deptCode.value = ''
}
</script>

<style scoped>

</style>
